/**
 * LocalStorage
 */

import { _decorator } from "cc";
import * as XXTEA from "../Plugins/XXTEA.js";

const XxteaDataKey = "au08f6ck-bfbd-5c";  //16
const GameId = "6666_"

const { ccclass, property } = _decorator;
@ccclass('LocalStorage')
export class LocalStorage {

    static _instance: LocalStorage;
    static get Instance() {
        if (this._instance) {
            return this._instance;
        }

        this._instance = new LocalStorage();
        return this._instance;
    }

    loadStorage(key : string)
    {
        if (!key) {
            return;
        }
        let data = localStorage.getItem(GameId + key);
        if (!data) {
            return null;
        }
    
        try {
            let decryptStr = XXTEA.decryptFromBase64(data , XxteaDataKey);
            data = decryptStr
        } catch (err) {
            console.error('[loadStorage] err:', err);
            //data = null;
        }
    
        let pObject: any = null;
        try {
            pObject = JSON.parse(data);
        } catch (e) {
            
        }
        if (pObject) {
            return pObject
        }
        return data;
    }

    
    /**
     * 存储
     */
    saveStorage(key: string, value) {
        try {
            value = JSON.stringify(value);
            //加密
            let encryptStr = XXTEA.encryptToBase64(value, XxteaDataKey);
            localStorage.setItem(GameId + key, encryptStr);
        } catch (error) {
            console.error(`saveStorage failed!`);
        }
    }


    isEncrypted(str : string)
    {
        try {
            let newStr = XXTEA.encryptToBase64(XXTEA.decryptFromBase64(str));
            if(str == newStr)
            {
                return true
            }
        } catch(e) {
            return false;
        }
        return false;
    }

    isNull(data : any)
    {
       if(data === '' || data === null || data === undefined)
       {
            return true;
       }
       return false;
    }

}


